package com.efast.dmom.mgmt.controller.excel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.efast.cafe.framework.bean.FileChunkInfo;
import com.efast.cafe.framework.bean.ResultBean;
import com.efast.dmom.mgmt.service.excel.QualityDataExcelUploadService;

/**
 * excel文件上传
 * 
 * @author wj
 * @date 2019/10/14 下午16：10
 */

@Controller
@RequestMapping(value = "/uploadExcelFile")
public class QualityExcelFileUploadController {

	@Autowired
	private QualityDataExcelUploadService qualityDataExcelUploadService;

	// iqc质量数据上传
	@RequestMapping(value = "/iqcUpload", method = RequestMethod.POST)
	public @ResponseBody ResultBean uploadIQCDataExcel(@RequestParam("files") MultipartFile mulFile,
			HttpServletResponse response, HttpServletRequest request, FileChunkInfo chunkInfo) throws IOException {
		ResultBean resultBean = new ResultBean(true, "'");
		if (mulFile == null || mulFile.isEmpty()) {
			resultBean.setSuccess(true);
			resultBean.setErrorCode("fail");
			resultBean.setMessage("上传失败，请检查文件是否为空！");
		} else if (mulFile.getSize() > 10000000) {
			resultBean.setSuccess(true);
			resultBean.setErrorCode("fail");
			resultBean.setMessage("上传失败，文件大小不能超过10M!！");
		} else {
			String rootPath = request.getServletContext().getRealPath("/") + "uploadExcel";
//	     File tempFile = FileUploadUtil.getReadySpace(chunkInfo, rootPath);
			// 文件所在的临时文件夹
			String fileName = chunkInfo.getFileName();
//	     String flodName = fileName.substring(0, fileName.lastIndexOf(".")) + chunkInfo.getUuid();
//	     String flodName=fileName.substring(0, fileName.lastIndexOf("."));
			File dir = new File(rootPath);
			if (!dir.exists()) {
				dir.mkdir();
			}
//			String chunkName = +fileName.substring(fileName.lastIndexOf('.'));
			File chunkFile = new File(dir, fileName);
			try {
				chunkFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
			mulFile.transferTo(chunkFile);
			Boolean flag = qualityDataExcelUploadService.IQCExcelUpload(chunkFile);
			chunkFile.delete();
			if (flag) {
				resultBean.setSuccess(true);
				resultBean.setErrorCode("success");
				resultBean.setMessage("文件上传成功");
			} else {
				resultBean.setSuccess(true);
				resultBean.setErrorCode("fail");
				resultBean.setMessage("表格字段与系统字段不一致，请检查字段后再试！");
			}
		}
		return resultBean;
	}

	// 售后质量数据上传
	@RequestMapping(value = "/afterQualityUpload", method = RequestMethod.POST)
	public @ResponseBody ResultBean afterQualityUpload(@RequestParam("files") MultipartFile mulFile,
			HttpServletResponse response, HttpServletRequest request, FileChunkInfo chunkInfo) throws IOException {
		ResultBean resultBean = new ResultBean(true, "'");
		if (mulFile == null || mulFile.isEmpty()) {
			resultBean.setSuccess(false);
			resultBean.setErrorCode("fail");
			resultBean.setMessage("上传失败，请检查文件是否为空！");
		} else if (mulFile.getSize() > 10000000) {
			resultBean.setSuccess(true);
			resultBean.setErrorCode("fail");
			resultBean.setMessage("上传失败，文件大小不能超过10M!！");
		} else {
			String rootPath = request.getServletContext().getRealPath("/") + "uploadExcel";
//		     File tempFile = FileUploadUtil.getReadySpace(chunkInfo, rootPath);
			// 文件所在的临时文件夹
			String fileName = chunkInfo.getFileName();
//		     String flodName = fileName.substring(0, fileName.lastIndexOf(".")) + chunkInfo.getUuid();
//		     String flodName=fileName.substring(0, fileName.lastIndexOf("."));
			File dir = new File(rootPath);
			if (!dir.exists()) {
				dir.mkdir();
			}
//				String chunkName = +fileName.substring(fileName.lastIndexOf('.'));
			File chunkFile = new File(dir, fileName);
			try {
				chunkFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
			mulFile.transferTo(chunkFile);
			boolean flag = qualityDataExcelUploadService.afterQualityUpload(chunkFile);
			chunkFile.delete();
			if (flag) {
				resultBean.setSuccess(true);
				resultBean.setErrorCode("success");
				resultBean.setMessage("文件上传成功");
			} else {
				resultBean.setSuccess(true);
				resultBean.setErrorCode("fail");
				resultBean.setMessage("表格字段与系统字段不一致，请检查字段后再试！");
			}
		}
		return resultBean;
	}

	// iqc和售后质量数据excel模板下载
	@RequestMapping(value = "/qualityExcelTemplateDownload/{excelName}", method = RequestMethod.POST)
	public @ResponseBody void iqcExcelTemplateDownload(@PathVariable String excelName,HttpServletResponse req, HttpServletResponse response) {
		try {
            InputStream fis = getResourcesFileInputStream("template/"+excelName+".xlsx");
            @SuppressWarnings("resource")
			XSSFWorkbook workbook = new XSSFWorkbook(fis);
            response.setContentType("application/binary;charset=ISO8859-1");
            String fileName = java.net.URLEncoder.encode(excelName, "UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");
            ServletOutputStream out = null;
            out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭文件输出流
        }
    }
	
	public static InputStream getResourcesFileInputStream(String fileName) {
	        return Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
	  }
}
